import fs from "fs/promises"
import md5 from "md5";
import {getRandomStr} from "../tools/index.js"
import {addUserDao,findUserDao,updateDao} from "../Dao/userDao.js"
import { gettoken } from "../token/jwt.js";
export const registerService = async ({username,nickname})=>{
    if(!nickname){
        nickname = "新用户" + getRandomStr(6)
    }
    const dirs = await fs.readdir("./static/avatar")
    const avatar = dirs[Math.floor(Math.random()*dirs.length)];
    return await addUserDao({
        username,
        nickname,
        avatar:"http://localhost:8090/"+avatar,
        password:md5("123123")
    })
}

export const loginService = async (userInfo)=>{
    //查询数据对比
    const user = await findUserDao(userInfo.username);
    if(user == null){
        return {
            code:1,
            msg:"用户名不存在"
        }
    }
    if(md5(userInfo.password) === user.password){
        //登录成功
        //是否要免密登录30天
        if(userInfo.noLogin){
            const token = gettoken(user.username,60*60*24*30);
            return{
                code:0,
                msg:"登录成功且免密登录30天",
                data:user,
                token
            }
        }else{
            //没有保存的
            const token = gettoken(user.username,60*60*24);
            return{
                code:0,
                msg:"登录成功",
                data:user,
                token
            }
        }
    }else{
        return {
            code:1,
            msg:"密码错误"
        }
    }
}

export const checkOldPass = async (userInfo)=>{
    const user = await findUserDao(userInfo.username);
    if(user != null){
        console.log("哈哈哈哈");
        if(md5(userInfo.oldpass) == user.password){
            return true
        }else{
            return false
        }
    }else{
        return false
    }
}

export const updatePass = async (userInfo)=>{
    const user = updateDao({...userInfo,password:md5(userInfo.confirmPass)})
    return user;
}
export const updateUserServ = async (username,updateObj)=>{
    const res = await updateDao(username,updateObj)
    console.log("username:",username);
    
    console.log("updateObj:",updateObj);
    
    return{
        code:0,
        msg:"ok",
        data:res
    }
}